<template>
  <el-dialog
    v-if="openForm"
    v-model="openBoole"
    :close-on-click-modal="false"
    custom-class="mydialog"
    width="50%"
    :title="title"
    @close="close"
  >
    <el-form
      ref="openRef"
      :model="openForm"
      :rules="rules"
      label-width="120px"
      size="small"
    >
      <el-row gutter="40">
        <el-col :span="24">
          <item-title title="基本信息" />
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="兼职人员姓名"
            prop="agent.userName"
          >
            <el-input
              v-model="openForm.agent.userName"
              clearable
              placeholder="请输入兼职人员姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="性别"
            prop="agent.sex"
          >
            <el-radio-group v-model="openForm.agent.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="兼职级别"
            prop="agent.agentLevel"
          >
            <el-select
              v-model="openForm.agent.agentLevel"
              style="width: 100%"
              placeholder="请选择兼职级别"
            >
              <el-option
                v-for="item in agentPersonLevel"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="联系电话"
            prop="agent.tel"
          >
            <el-input
              v-model="openForm.agent.tel"
              clearable
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="身份证"
            prop="agent.cardNumber"
          >
            <el-input
              v-model="openForm.agent.cardNumber"
              clearable
              placeholder="请输入身份证号码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="详细地址"
            prop="agent.address"
          >
            <el-input
              v-model="openForm.agent.address"
              clearable
              placeholder="请输入详细地址"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="身份证附件"
            prop="agent.cardFiles"
          >
            <div class="qualityFiles-container">
              <div
                v-for="(item,index) in openForm.agent.cardFiles"
                :key="index"
                class="file-item"
              >
                <image-upload-view
                  ref="imageUploadView"
                  :data="item"
                />
              </div>
            </div>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24">-->
        <!--          <item-title title="合同信息"/>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="合同名称" prop="contract.contractName">-->
        <!--            <el-input v-model="openForm.contract.contractName" clearable placeholder="请输入合同名称"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="合同类型" prop="contract.contractObjectType">-->
        <!--            <el-select v-model="openForm.contract.contractObjectType" disabled style="width: 100%"-->
        <!--                       placeholder="请选择合同类型">-->
        <!--              <el-option v-for="item in contractTypeData" :key="item.id" :label="item.label" :value="item.value"/>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="合同日期" prop="date">-->
        <!--            <el-date-picker-->
        <!--              @change="handlDate"-->
        <!--              style="width: 100%"-->
        <!--              v-model="openForm.date"-->
        <!--              type="daterange"-->
        <!--              range-separator="至"-->
        <!--              start-placeholder="开始日期"-->
        <!--              end-placeholder="结束日期">-->
        <!--            </el-date-picker>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="合同负责人" prop="contract.contractHeadId">-->
        <!--            <el-select v-model="openForm.contract.contractHeadId" style="width: 100%"-->
        <!--                       @change="handlChangeHead"-->
        <!--                       placeholder="请选择合同负责人">-->
        <!--              <el-option-->
        <!--                v-for="item in headList"-->
        <!--                :key="item.id"-->
        <!--                :label="item.userName"-->
        <!--                :value="item.id"/>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="归属部门" prop="contract.contractDepartmentId">-->
        <!--            <el-cascader :popper-append-to-body="false"  style="width:100%"-->
        <!--                         v-model="openForm.contract.contractDepartmentId" @change="handlCascader"-->
        <!--                         placeholder="请选择归属部门" :options="departmentList"-->
        <!--                         :props="{  checkStrictly: true, value:'parentId',label:'deptName' }"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="合同金额" prop="contract.contractAmount">-->
        <!--            <el-input v-model="openForm.contract.contractAmount" @change="handlAmount" clearable placeholder="请输入合同金额"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="合同附件" prop="contract.contractFile">-->
        <!--            <upload-file-view :fileArr.sync="openForm.contract.contractFile" ref="uploadFileView"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          style="margin-right: 20px;"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="handlSubmit"
        >保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, nextTick, onMounted, reactive, toRefs,} from 'vue'
import area from '@/utils/area'
import {validateVEIdCard, validateVENumber, validateVETel,} from '@/utils/validate'
import {crmStore} from '@CRM/store'

export default {
  name: 'FormPersonnel',
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else {
        if (validateVETel(value)) {
          callback(new Error('手机号格式不正确'))
        } else {
          callback()
        }
      }
    }

    const validateNum = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback()
      } else {
        if (validateVENumber(value)) {
          callback(new Error('格式不正确(最多保留两位小数)'))
        } else {
          callback()
        }
      }
    }

    const validateCardFiles = (rule, value, callback) => {
      if (data.openForm.agent.cardFiles.length === 0) {
        callback(new Error('请上传身份证'))
      } else {
        for (let i = 0; i < data.openForm.agent.cardFiles.length; i++) {
          const a = data.openForm.agent.cardFiles[i]
          if (a.url === '') {
            callback(new Error('请上传身份证'))
          } else {
            callback()
          }
        }
      }
    }

    const validateIdCard = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('身份证不能为空'))
      } else {
        if (validateVEIdCard(value)) {
          callback(new Error('格式不正确'))
        } else {
          callback()
        }
      }
    }
    //* ********************************
    const api = inject('api')
    var data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        date: null,
        agent: {
          agentLevel: '', // 代理级别
          userName: '',
          tel: '',
          sex: '1',
          cardNumber: '',
          address: '',
          cardFiles:
            crmStore.getters['jsonData/getJsonData'][
              'part_person_qualification'
            ].data || [],
        },
        contract: {
          contractName: '',
          contractObjectType: 'agent',
          contractBeginTime: '',
          contractEndTime: '',
          contractHeadName: '', // 合同负责人
          contractHeadId: null, // 合同负责人id
          contractDepartmentName: '', // 合同归属部门
          contractDepartmentId: null, // 合同归属部门
          contractAmount: null,
          contractFile: [],
        },
      },
      openRef: null,
      title: '新建兼职人员',
      rules: {
        'agent.userName': [
          { required: true, message: '请输入兼职人员', trigger: 'blur' },
        ],
        'agent.agentLevel': [
          { required: true, message: '请选择代理商级别', trigger: 'change' },
        ],
        // 'agent.address': [{required: true, message: '请输入详细地址', trigger: 'blur',}],
        'agent.cardNumber': [
          { required: true, validator: validateIdCard, trigger: 'blur' },
        ],
        'agent.tel': [
          { required: true, validator: validateTel, trigger: 'blur' },
        ],
        date: [
          { required: true, message: '请选择合同日期', trigger: 'change' },
        ],
        'contract.contractName': [
          { required: true, message: '请输入合同名称', trigger: 'blur' },
        ],
        'contract.contractAmount': [
          { validator: validateNum, trigger: 'blur' },
        ],
        'agent.cardFiles': [
          { required: true, validator: validateCardFiles, trigger: 'blur' },
        ],
      },
      contractTypeData:
        crmStore.getters['dictionary/getDictionary']['contract_type'],
      contractObjectTypeData:
        crmStore.getters['dictionary/getDictionary']['contract_object'],
      agentlevelData:
        crmStore.getters['dictionary/getDictionary']['agent_level'],
      agentPersonLevel:
        crmStore.getters['dictionary/getDictionary']['agent_person_level'],
      imageUploadView: null,
      uploadFileView: null,
      headList: [],
      departmentList: [],
    })
    const currentInstance = getCurrentInstance()

    const handlCity = (val) => {
      if (val) {
        openForm.provinceCode = val[1]
        openForm.cityCode = val[2]
        openForm.areaCode = val[3]
        nextTick((_) => {
          openRef.value.clearValidate('provinceCode')
        })
      }
    }

    const close = () => {
      data.openBoole = false
      handlRemove()
    }

    const handlRemove = () => {
      data.openRef.clearValidate()
      data.openRef.resetFields()
    }

    const handlDate = (val) => {
      if (val) {
        data.openForm.contract.contractBeginTime = val[0]
        data.openForm.contract.contractEndTime = val[1]
      }
    }

    const handlAmount = (val) => {
      data.openForm.contract.contractAmount = Number(val)
    }

    const open = (val, num) => {
      data.openForm = {
        date: null,
        agent: {
          agentLevel: '', // 代理级别
          userName: '',
          tel: '',
          sex: '1',
          cardNumber: '',
          address: '',
          cardFiles:
            JSON.parse(
              JSON.stringify(
                crmStore.getters['jsonData/getJsonData'][
                  'part_person_qualification'
                ].data
              )
            ) || [],
        },
        contract: {
          contractName: '',
          contractObjectType: 'agent',
          contractBeginTime: '',
          contractEndTime: '',
          contractHeadName: '', // 合同负责人
          contractHeadId: null, // 合同负责人id
          contractDepartmentName: '', // 合同归属部门
          contractDepartmentId: null, // 合同归属部门
          contractAmount: null,
          contractFile: [],
        },
      }
      if (num === 1) {
        data.title = '新建兼职人员'
      }
      if (num === 2) {
        data.title = '编辑兼职人员'
      }
      if (val) {
        handlDetail(val)
      }

      data.openBoole = true
    }

    // 获取负责人
    const handlHead = () => {
      console.log(3333333333333)
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          data.headList = res.data
        }
      })
    }

    // 负责人事件
    const handlChangeHead = (val) => {
      const index = data.headList.findIndex((a) => a.id === val)
      if (index !== -1) {
        data.openForm.contract.contractHeadName = data.headList[index].userName
      }
    }

    const handlDepartment = () => {
      api.terminal.DEPARTMENT_LIST().then((res) => {
        if (res.code === 0) {
          data.departmentList = res.data
        }
      })
    }

    const handlCascader = (val) => {
      if (val) {
        const a = handlRecursive(data.departmentList, val[val.length - 1])
        data.openForm.contract.contractDepartmentId = a[a.length - 1].id
        data.openForm.contract.contractDepartmentName = a[a.length - 1].name
      }
    }

    const handlRecursive = (arr, id) => {
      let oldList = []
      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i].parentId) {
          oldList.push({ id: arr[i].parentId, name: arr[i].deptName })
          return oldList
        } else if (arr[i].children && arr[i].children.length > 0) {
          const newList = handlRecursive(arr[i].children, id)
          if (newList && newList.length > 0) {
            oldList.push({ id: arr[i].parentId, name: arr[i].deptName })
            oldList = oldList.concat(newList)
            return oldList
          }
        }
      }
    }

    const handlFile = () => {
      data.openForm.contract.contractFile.forEach((item) => {
        // item.url = item.Value
        // item.name = item.Key
        item.code = ''
        item.isLong = 1
        item.isNeed = 1
        item.type = 1
        item.validTime = ''
      })
    }

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          let msg = ''
          if (data.openForm.agent.id !== undefined) {
            msg = '编辑成功'
          } else {
            msg = '创建成功'
          }
          api.channelAgent.PARTTIMEBIGBAG_CREATE(data.openForm).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: msg,
              })
              context.emit('succsess')
              close()
            } else {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            }
          })
        }
      })
    }

    const handlDetail = async(id) => {
      const res = await api.channelAgent.POTENTIALAGENT_DETAIL(id)
      if (res.code === 0) {
        const dataAgent = reactive(res.data.agent)
        for (const key in data.openForm.agent) {
          data.openForm.agent[key] = dataAgent[key]
        }
        data.openForm.agent.id = dataAgent.id
      }
      // let ress = await api.channelAgent.POTENTIALAGENT_CONTRACT_DETAIL(id)
      // if (ress.code === 0) {
      //   let dataContract = reactive(ress.data.contract)
      //   for (let key in data.openForm.contract) {
      //     data.openForm.contract[key] = dataContract[key]
      //   }
      //   // data.openForm.contract.contractFile.forEach(item => {
      //   //   item.Key = item.name
      //   //   item.Value = item.url
      //   // })
      //   data.openForm.contract.id = dataContract.id
      //   data.openForm.date = [data.openForm.contract.contractBeginTime, data.openForm.contract.contractEndTime]
      // }
    }

    onMounted((_) => {
      handlHead()
      handlDepartment()
    })

    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlCity,
      handlRemove,
      handlDate,
      handlAmount,
      handlDetail,
      handlFile,
      handlHead,
      handlChangeHead,
      handlDepartment,
      handlCascader,
    }
  },
}
</script>

<style lang="scss" scoped>
</style>
